package com.roosterrobotics.replicant;


import com.roosterrobotics.replicant.provider.ReplicantData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class ReplicantActivity extends ListActivity {
	
	private static final int ADD_ID = Menu.FIRST;
	private static final int DELETE_ID = Menu.FIRST + 1;
	private static final int UPDATE_ID = Menu.FIRST + 2;
	private ContentProviderClient client;
	private ContentProvider provider;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = getContentResolver().acquireContentProviderClient(ReplicantData.AUTHORITY);
        provider = client.getLocalContentProvider();
        setContentView(R.layout.main);
        setTitle(R.string.community_list);
        fillData();
        ListView lv = getListView();
        registerForContextMenu(lv);
        
     lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
        		Cursor c = provider.query(Uri.parse(ReplicantData.Communities.CONTENT_URI + "/" + String.valueOf(id)),
        				null, null, null, null);
        		if (c != null) {
        			c.moveToFirst();
        			String name = c.getString(c.getColumnIndex(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME));
        			Long c_id = c.getLong(c.getColumnIndex(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME));
        			Bundle b = new Bundle();
        			b.putString(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME, name);
        			b.putLong(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME, c_id);
        			c.close();
        			Intent i = new Intent(ReplicantActivity.this, CommunityDetail.class);
        			i.putExtras(b);
        			startActivity(i);	
        		}
        	}
        });
        
        		        
        
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
    	menu.add(0, ADD_ID, 0, R.string.community_add);
        return result;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case ADD_ID:
    		Intent i = new Intent(this, CommunityUpdate.class);
    		startActivityForResult(i, ADD_ID);
    		return true;
    	}
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) {
    	super.onCreateContextMenu(menu, v, info);
    	menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    	menu.add(0, UPDATE_ID, 0, R.string.menu_update);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	switch(item.getItemId()) {
    	case DELETE_ID:
    		provider.delete(Uri.parse(ReplicantData.Communities.CONTENT_URI + "/" + String.valueOf(info.id)),
    		null, null);
    		fillData();
    		return true;
    	case UPDATE_ID:
    		//TODO: Pasar esto a la actividad, que sea autocontenida.
    		Cursor c = provider.query(Uri.parse(ReplicantData.Communities.CONTENT_URI + "/" + String.valueOf(info.id)),
        				null, null, null, null);
    		if (c != null) {
    			Intent i = new Intent(this, CommunityUpdate.class);
    			Bundle b = new Bundle();
    			c.moveToFirst();
    			b.putLong(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME, 
    					c.getLong(c.getColumnIndexOrThrow(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME)));
    			b.putString(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME, 
    					c.getString(c.getColumnIndexOrThrow(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME)));
    			i.putExtras(b);
    			c.close();
    			startActivityForResult(i, UPDATE_ID);
    		}
    		return true;
    		
    		
    	}
    		
    	return super.onContextItemSelected(item);
    }
    
    
    private void fillData() {
    	ContentResolver cr = getContentResolver();
    	Cursor c = cr.query(ReplicantData.Communities.COMMUNITIES_URI, null, null, null, null);
    	if (c != null) {
    		startManagingCursor(c);
    	}
    	String[] from = new String[] {ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME};
    	int[] to = new int[] {R.id.text1};
    	
    	SimpleCursorAdapter communities = new SimpleCursorAdapter(this, R.layout.communities_row, c, from, to);
    	setListAdapter(communities);
    }
    
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Long id;
        String name;
        Bundle extras = null;
        
        switch (requestCode) {
        case UPDATE_ID:
        	if (resultCode == Activity.RESULT_OK) {
        		extras = intent.getExtras();
        		id = extras.getLong(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME);
        		name = extras.getString(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME);
        		ContentValues values = new ContentValues();
        		values.put(ReplicantData.Communities.COMMUNITY_ID_COLUMN_NAME, id);
        		values.put(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME, name);
        		provider.update(Uri.parse(ReplicantData.Communities.COMMUNITIES_URI + "/" + String.valueOf(id)), 
        				values, null, null);
        	}
        	break;
        case ADD_ID:
        	if (resultCode == Activity.RESULT_OK) {
        		Uri retUri;
        		extras = intent.getExtras();
        		name = extras.getString(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME);
        		ContentValues values = new ContentValues();
        		values.put(ReplicantData.Communities.COMMUNITY_NAME_COLUMN_NAME, name);
        		retUri = provider.insert(ReplicantData.Communities.COMMUNITIES_URI, values);
        		long commId = ContentUris.parseId(retUri);
        		if (commId < 0) {
        			duplicatedCommunity();
        		}
        	}
        	break;
        }
        
    }
	
	private void duplicatedCommunity() {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.duplicated_community)
			.setCancelable(false)
			.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();							
				}
			});
			AlertDialog alert = builder.create();
			alert.show();		
	}
}